/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.result;

import java.net.*;
import javax.net.*;
import java.util.*;

public class ResultServer extends Thread {
	private int port = -1;
	private Vector<ResultMarshall> resultMarshalls = new Vector<ResultMarshall>();

	public ResultServer(int portNum) {
		this.port = portNum;
	}

	public void run() {
		try {
			System.out.println(
				"Result Server: Listening on port " + port + ".");
			ServerSocketFactory ssf = ServerSocketFactory.getDefault();
			ServerSocket ss = ssf.createServerSocket(port);
			while (true) {
				new ResultSocket(ss.accept(), this).start();
				//System.out.println("Result Server: Opened new result socket.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addResultMarshall(ResultMarshall rm) {
		if (rm == null)
			return;
		for (int i = 0; i < resultMarshalls.size(); i++) {
			ResultMarshall rm2 = (ResultMarshall)resultMarshalls.elementAt(i);
			if (rm2.queryID == rm.queryID) {
				System.err.println("Failed to add result marshall. Result marshall with ID " + rm.queryID + " already exists!");	
				return;
			}	
		}
		resultMarshalls.addElement(rm);
		//System.out.println("Added ResultMarshall: " + rm.toString());
	}

	public ResultMarshall getResultMarshall(int queryID) {
		for (int i = 0; i < resultMarshalls.size(); i++) {
			
			ResultMarshall rm = (ResultMarshall) resultMarshalls.elementAt(i);
			if (rm.queryID == queryID) {
				//System.out.println("FOUND MATCH: " + queryID + ", " + rm.toString());
				return rm;
			}
		}
		return null;
	}

	public void removeResultMarshall(int queryID) {
		for (int i = 0; i < resultMarshalls.size(); i++) {
			ResultMarshall rm = (ResultMarshall) resultMarshalls.elementAt(i);
			if (rm.queryID == queryID) {
				resultMarshalls.removeElementAt(i);
				break;
			}
		}
	}

}
